package com.misty.blog.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.misty.blog.service.ConcernListService;
import com.misty.blog.service.UsersService;
import com.misty.common.Util.RedisCache;
import com.misty.common.bean.Result;
import com.misty.common.constants.RedisKey;
import com.misty.dao.domain.ConcernList;
import com.misty.dao.domain.Users;
import com.misty.dao.mapper.ConcernListMapper;
import com.misty.dao.mapper.UsersMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author cthulhu
 * @since 2022-11-21
 */
@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements UsersService {

    @Resource
    private UsersMapper usersMapper;
    @Resource
    private ConcernListMapper concernListMapper;

    @Autowired
    private ConcernListService concernListService;

    @Autowired
    private RedisCache redisCache;

    /**
     *
     * @Param
     * @return
     * @Description 查询单个用户
     * @Date
     **/
    @Override
    public Users selectOne(Users users) {
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(StrUtil.isNotBlank(users.getUsername()),Users::getUsername,users.getUsername())
                .eq(users.getId() != null,Users::getId,users.getId());
        Users user = usersMapper.selectOne(queryWrapper);
        return user;
    }

    /**
     *
     * @Param
     * @return
     * @Description 根据ID查询用户
     * @Date
     **/
    @Override
    public Users selectByUserId(Integer userId){
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("users.id",userId);
        return usersMapper.selectByUserId(queryWrapper);
    }

    @Override
    @Transactional(transactionManager = "mistyTransactionManager")
    public Result<?> concern(ConcernList concernList) {

        redisCache.clearCache(RedisKey.BLOG_DETAIL);

        Boolean concernType = concernListService.isConcern(null, concernList.getUserId(), concernList.getFollowUserId());

        LambdaUpdateWrapper<Users> updateWrapper = Wrappers.<Users>lambdaUpdate()
                .eq(Users::getId, concernList.getUserId());

        if(concernType){
            //已关注
            updateWrapper.setSql("concern_count = concern_count - 1");
        }else {
            //未关注
            updateWrapper.setSql("concern_count = concern_count + 1");
        }

        int update = usersMapper.update(null, updateWrapper);
        if(update <= 0 ){
            return Result.error("关注失败!");
        }

        int sccessfulCount;
        Wrapper<ConcernList> concernListWrapper = Wrappers
                .<ConcernList>lambdaUpdate()
                .eq(ConcernList::getUserId, concernList.getUserId())
                .eq(ConcernList::getFollowUserId, concernList.getFollowUserId());

        if(concernType){
            //已关注
            updateWrapper.setSql("concern_count = concern_count - 1");
            sccessfulCount = concernListMapper.delete(concernListWrapper);
        }else {
            //未关注
            concernList.setCreateTime(LocalDateTime.now())
                    .setUpdateTime(LocalDateTime.now());
            updateWrapper.setSql("concern_count = concern_count + 1");
            sccessfulCount = concernListMapper.insert(concernList);
        }


        if(sccessfulCount <= 0 ){
            return Result.error("关注失败!");
        }
        return Result.success("关注成功!",concernType);
    }

    @Override
    public int getConcernCount(Integer userId){
        Users users = this.selectOne(
                new Users()
                        .setId(userId)
        );
        return users.getConcernCount();
    }

    @Override
    public Result<?> getConcernList(ConcernList concernList) {
        Wrapper<ConcernList> concernListWrapper = Wrappers
                .<ConcernList>lambdaQuery()
                .eq(ConcernList::getUserId, concernList.getUserId());

        List<ConcernList> concernLists = concernListMapper.selectList(concernListWrapper);
        List<Integer> ids = concernLists.stream()
                .map(list -> list.getFollowUserId())
                .collect(Collectors.toList());

        List<Users> users = usersMapper.selectBatchIds(ids);
        Map<String,String> nameMap;
        List<Object> usernameList = users.stream()
                .map(user -> user.getUsername())
                .distinct()
                .map(username-> {
                    Map<String, String> map = new HashMap<>();
                    map.put("username",username);
                    return map;
                })
                .collect(Collectors.toList());

        return Result.success("获取关注列表!",usernameList);
    }
}
